package org.kele.k8s.sc2020.provider.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alicp.jetcache.anno.support.SpringConfigProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Function;

@Slf4j
@Configuration
public class JecCacheConfiguration {

    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    @Bean
    public SpringConfigProvider springConfigProvider() {
        log.info("自定义json 序列化");
        return new SpringConfigProvider() {
            @Override
            public Function<Object, byte[]> parseValueEncoder(String valueEncoder) {
                if (valueEncoder.equalsIgnoreCase("fastjson")) {
                    return obj -> JSON.toJSONBytes(obj, SerializerFeature.WriteClassName);
                }
                return super.parseValueEncoder(valueEncoder);
            }

            @Override
            public Function<byte[], Object> parseValueDecoder(String valueDecoder) {
                if (valueDecoder.equalsIgnoreCase("fastjson")) {
                    return JSON::parse;
                }
                return super.parseValueDecoder(valueDecoder);
            }
        };
    }
}
